from django.shortcuts import render
from django.http import HttpResponse
import requests
import lxml
from bs4 import BeautifulSoup
import json
import os

# from PIL import Image


s = requests.session()
id = ""
password = ""
user_num = 10619

temp_num = 0

total_score_temp = 0
total_grade_point = 0
com_score = 0
com_grade_point = 0


def get_session_code(request):
    global s
    global user_num
    user_num = user_num + 1
    user_temp = user_num
    s = requests.session()
    url = 'http://zhjw.scu.edu.cn/login'
    r = s.get(url)
    J_sess = r.headers['Set-Cookie'][11:-8]

    code_url = "http://zhjw.scu.edu.cn/img/captcha.jpg?80"
    headers = {
        "Cookie": "JSESSIONID=" + J_sess,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
        "Referer": "http://zhjw.scu.edu.cn/login"
    }
    r = s.get(code_url, headers=headers)
    with open("/django/scuscore/image/code" + str(user_temp) + ".jpg", "wb") as f:
        f.write(r.content)
    data_2 = '''
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>成绩查询</title>
</head>
<body>
    <div class="jumbotron">
    <div align="center">
        <h2>均分均绩查询</h2>
        <h3><small>万恶之原</small><h3>
            <button  class="btn btn-primary" type="button">
                查询人数<span class="badge" id="user_num"></span>
                </button>
            <button class="btn btn-primary" type="button">
                当前川大人均平均分<span id="av_score" class="badge"></span>
                </button>
                <button class="btn btn-primary" type="button">
                当前川大人均必修平均分<span id="av_com_score" class="badge"></span>
                </button>
            <button class="btn btn-primary" type="button">
                当前川大人均绩点<span id="av_point" class="badge"></span>
                </button>
                <button class="btn btn-primary" type="button">
                当前川大人均必修绩点<span id="av_com_point" class="badge"></span>
                </button>

            <div class='form-group'>
                <label for='exampleInputEmail1'>学号</label>
                <input type='text' class="form-control" id="id" placeholder="请输入学号" name="id">
            </div>
            <div class='form-group'>
                <label for='exampleInputEmail1'>密码</label>
                <input type='password' class="form-control" id="pass" placeholder="请输入教务系统密码" name="password">
            </div>
            ''' + "<input id='J_sess' type='hidden' value=" + J_sess + " name='J_sess'>" + "<input type='hidden' value=" + str(
        user_temp) + " id='user'>" + '''
            <img class="img-thumbnail" src='/image/code''' + str(user_temp) + '''.jpg'/>
            <br>
            <div class='form-group'>
                <label for='exampleInputEmail1'>验证码</label>
                <input type='text' class="form-control" id="code" placeholder="请输入图中验证码进行验证" name="code">
            </div>
            <button class="btn btn-info" type="button" id="pj">查询</button>



    </div>
    </div>
<div id="info">
        </div>
        </body>
</html>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(function() {
        $.ajax({
            url:'http://119.23.231.17:6060/info',
            success:function(data){
                $('#user_num').append(JSON.parse(data).user_num);
                $('#av_score').append(JSON.parse(data).user_total_score);
                $('#av_com_score').append(JSON.parse(data).com_score);
                $('#av_point').append(JSON.parse(data).total_grade_point);
                $('#av_com_point').append(JSON.parse(data).com_grade_point);
            }
        })
        $('#pj').click(function () {
            $('#pj').attr({'disabled':'disabled'});
            // $('#info').get('http://119.23.231.17:6060/score?id='+$('#id').val()+"&password="+$("#pass").val()+"&J_sess=" + $('#J_sess').val() +"&code=" + $('#code').val());
            $.ajax({
                url:'http://119.23.231.17:6060/score?id='+$('#id').val()+"&password="+$("#pass").val()+"&J_sess=" + $('#J_sess').val() +"&code=" + $('#code').val() + "&User=" + $("#user").val(),
                method:'GET',
                success:function(data){
                    var total_credit = 0;
                    var total_score = 0;
                    var total_gradepoint = 0;
                    var compulsory_credit = 0;
                    var compulsory_score = 0;
                    var compulsory_gradepoint = 0;
                    var inner = "<table class='table table-bordered'><tr><td colspan='9'>已出成绩科目</td></tr><tr><td>课程名</td><td>平均分</td><td>最高分</td><td>你的成绩</td><td>排名</td><td>绩点</td><td>成绩级别</td><td>课程属性</td><td>学分</td></tr>";
                    for(var item in JSON.parse(data)[0].list){
                        if(JSON.parse(data)[0].list[item].courseScore != ""){
                            inner += "<tr>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].courseName +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].avgcj +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].maxcj +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].courseScore +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].rank +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].gradePoint +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].levelName +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].coursePropertyName +"</td>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].credit +"</td>";
                            inner += "</tr>";
                            total_credit += JSON.parse(data)[0].list[item].credit;
                            total_score += JSON.parse(data)[0].list[item].courseScore * JSON.parse(data)[0].list[item].credit;
                            total_gradepoint += JSON.parse(data)[0].list[item].gradePoint * JSON.parse(data)[0].list[item].credit;
                            if(JSON.parse(data)[0].list[item].coursePropertyName == "必修"){
                                compulsory_gradepoint += JSON.parse(data)[0].list[item].gradePoint * JSON.parse(data)[0].list[item].credit;
                                compulsory_score += JSON.parse(data)[0].list[item].courseScore * JSON.parse(data)[0].list[item].credit;
                                compulsory_credit += JSON.parse(data)[0].list[item].credit;
                            }
                        }
                    }
                    inner += "<tr><td colspan='9'>未出成绩科目</td></tr>";
                    inner += "<tr><td>课程名<td colspan='4'>课程属性</td><td colspan='4'>学分</td></tr>";
                    for(var item in JSON.parse(data)[0].list){
                        if(JSON.parse(data)[0].list[item].courseScore == ""){
                            inner += "<tr>";
                            inner += "<td>"+ JSON.parse(data)[0].list[item].courseName +"</td>";
                            inner += "<td colspan='4'>"+ JSON.parse(data)[0].list[item].coursePropertyName +"</td>";
                            inner += "<td colspan='4'>"+ JSON.parse(data)[0].list[item].credit +"</td>";
                            inner += "</tr>";
                        }
                    }
                    inner += "<tr><td colspan='9'>绩点均分信息</td></tr>";
                    inner += "<tr><td colspan='3'>全部均分</td><td colspan='6'>全部平均绩点</td></tr>";
                    inner += "<tr><td colspan='3'>" + (total_score/total_credit) +"</td><td colspan='6'>" + (total_gradepoint/total_credit) + "</td></tr>";
                    inner += "<tr><td colspan='3'>必修均分</td><td colspan='6'>必修平均绩点</td></tr>";
                    inner += "<tr><td colspan='3'>" + (compulsory_score/compulsory_credit) +"</td><td colspan='6'>" + (compulsory_gradepoint/compulsory_credit) + "</td></tr>";
                    inner += "</table>";
                    $("#info").append(inner);
                },
                error:function(){
                    $("#info").append('<div class="jumbotron"><h2 align="center">出现了某些错误，请检查学号密码，刷新后重新尝试！</h2></div>');
                }

            })
        })
    })
</script>

    '''
    return HttpResponse(data_2)


def returnData(request):
    global total_score_temp
    global com_score
    global total_grade_point
    global com_grade_point
    global temp_num
    id = request.GET["id"]
    password = request.GET["password"]
    code = request.GET["code"]
    J_sess = request.GET["J_sess"]
    user_num = request.GET["User"]
    data = {
        "j_username": id,
        "j_password": password,
        "j_captcha": code
    }
    headers = {
        "Cookie": "JSESSIONID=" + J_sess,
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0",
        "Referer": "http://zhjw.scu.edu.cn/login"
    }
    url_login = "http://zhjw.scu.edu.cn/j_spring_security_check"
    r = s.post(url_login, headers=headers, data=data)

    score_url = "http://zhjw.scu.edu.cn/student/integratedQuery/scoreQuery/thisTermScores/data"

    score_json = s.get(score_url, headers=headers)

    json_data = json.loads(score_json.text)[0]["list"]

    os.rename("/django/scuscore/image/code" + str(user_num) + ".jpg", "/django/scuscore/image/" + code + ".jpg")

    temp_num += 1

    grade_score = 0
    total_grade_score = 0
    total_score = 0
    total_compulsory_score = 0
    total_compulsory_grade_score = 0
    total_compulsory_credit = 0

    info_str = ""

    for item in json_data:
        if item["courseScore"] != "":
            info_str += "课程名：" + str(item["courseName"]) + "\t\t\t\t\t\t平均分：" + str(item["avgcj"]) + "\t最高分：" + item[
                "maxcj"] + "\t你的成绩：" + str(item["courseScore"]) + "\t绩点:" + str(item["gradePoint"]) + "<br>"
            total_grade_score += item["credit"] * item["gradePoint"]
            total_score += float(item["credit"]) * float(item["courseScore"])
            grade_score += item["credit"]
            if item["coursePropertyName"] == "必修":
                total_compulsory_score += float(item["credit"]) * float(item["courseScore"])
                total_compulsory_grade_score += float(item["gradePoint"]) * float(item["credit"])
                total_compulsory_credit += item["credit"]
    info_str += "<br>全部平均绩点是：" + str(round(total_grade_score / grade_score, 3))
    info_str += "<br>必修绩点是：" + str(round(total_compulsory_grade_score / total_compulsory_credit, 3))
    info_str += "<br>全部平均分是：" + str(round(total_score / grade_score, 3))
    info_str += "<br>必修平均分是：" + str(round(total_compulsory_score / total_compulsory_credit, 3))

    total_score_temp += round(total_score / grade_score, 3)
    com_score += round(total_compulsory_score / total_compulsory_credit, 3)
    total_grade_point += round(total_grade_score / grade_score, 3)
    com_grade_point += round(total_compulsory_grade_score / total_compulsory_credit, 3)

    data_html = '''
        <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>查询结果</title>
</head>
<body>
    ''' + info_str + '''
</body>
</html>
    '''
    return HttpResponse(score_json.text)


def returnInfo(request):
    global user_num
    global total_score_temp
    global com_score
    global total_grade_point
    global com_grade_point
    global temp_num
    if temp_num != 0:
        return HttpResponse('{"user_num":' + str(user_num) + ',"user_total_score":' + str(
            total_score_temp / temp_num) + ',"com_score":' + str(com_score / temp_num) + ',"total_grade_point":' + str(
            total_grade_point / temp_num) + ',"com_grade_point":' + str(com_grade_point / temp_num) + '}')
    else:
        return HttpResponse('{"user_num":' + str(user_num) + ',"user_total_score":' + str(0) + ',"com_score":' + str(
            0) + ',"total_grade_point":' + str(0) + ',"com_grade_point":' + str(0) + '}')
